package com.zhisuo.apicenter.aes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;

public class GetPhoneNumber {
	
	private static final String WATERMARK = "watermark";
	private static final String APPID = "wx421320f3d6d41aff";
	
	private static boolean hasInited = false;

    public static void init() {
        if (hasInited) {
            return;
        }
        Security.addProvider(new BouncyCastleProvider());
        hasInited = true;
    }

    public static String decrypt(String session_key, String iv, String encryptData) {
    	
        String decryptString = "";
        init();
        byte[] sessionKeyByte = Base64.decodeBase64(session_key);
        byte[] ivByte = Base64.decodeBase64(iv);
        byte[] encryptDataByte = Base64.decodeBase64(encryptData);
        try {
        	
        	  int base = 16;
              if (sessionKeyByte.length % base != 0) {
                  int groups = sessionKeyByte.length / base + (sessionKeyByte.length % base != 0 ? 1 : 0);
                  byte[] temp = new byte[groups * base];
                  Arrays.fill(temp, (byte) 0);
                  System.arraycopy(sessionKeyByte, 0, temp, 0, sessionKeyByte.length);
                  sessionKeyByte = temp;
              }
        	
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key key = new SecretKeySpec(sessionKeyByte, "AES");
            AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance("AES");
            algorithmParameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, key, algorithmParameters);
            byte[] bytes = cipher.doFinal(encryptDataByte);
            decryptString = new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptString;
    }
    
    public static void main(String[] args) {
    	String appId = "wx421320f3d6d41aff";
        String session_key = "4BaP0nEy9kaUb1AwQrzIDg==";
        String iv = "4BaP0nEy9kaUb1AwQrzIDg==";
        String encryptData ="STyDkBJe66KT7PiJBn+rqF9rI0rB4pNwbDE0B5Rk60Lf+G8Plo7yemOijDfAf8jwqjHhSXmwp2yk1/RWSCamEG6b6GPQ/hBrsSF0RNM57BgvzgpJA+6WyiKd6dL5sdzsFoATKCAKcyP2VJvIyTxNG1/A+SAneidssJsNk36FkpVtYn94k8465j9BoNruAJsnXCCLzmCzUoxGIy/vTur/LQ==";
        String decrypt = decrypt(session_key, iv, encryptData);
        JSONObject jsonObject = JSON.parseObject(decrypt);
        System.out.println(jsonObject);
    	
     
    }
}
